import random

import logging
from django.http import HttpResponse
from django.shortcuts import render

# Create your views here.
# 获取图片验证码 get的形式
from django_redis import get_redis_connection
from rest_framework.generics import GenericAPIView
from rest_framework.response import Response
from rest_framework.views import APIView

from celery_tasks.sms.tasks import send_sms_code
from meiduo_mall.libs.captcha.captcha import captcha
from users.models import User
from verifications.serializers import ImageCodeCheckSerialzier

logger = logging.getLogger('django')


class ImageCodeView(APIView):
    def get(self, request, image_code_id):
        # 1.获取参数
        # 2.校验参数
        # 3.生成图片验证码
        text, image = captcha.generate_captcha()
        # 生成一个可操作的redis连接对象 储存生成的验证信息
        redis_conn = get_redis_connection('verify_codes')
        redis_conn.setex('img_%s' % image_code_id, 300, text)
        # 4.返回图片验证码
        return HttpResponse(image, content_type='image/jpg')


class SmsVerificationView(GenericAPIView):
    # 短信验证 请求:GET /sms_codes/{mobile}/?image_code_id=xxx&text=xxx
    serializer_class = ImageCodeCheckSerialzier

    def get(self, request, mobile):
        # 1.获取参数
        data = request.query_params
        # 2.验证参数 引入序列器
        serializer = self.get_serializer(data=data)
        serializer.is_valid(raise_exception=True)

        sms_code = '%06d' % random.randint(0, 999999)
        # 4.保存短信验证码和发短信的动作
        redis_conn = get_redis_connection('verify_codes')
        pl = redis_conn.pipeline()
        pl.setex('send_flag_%s' % mobile, 60, 1)
        pl.setex("sms_%s" % mobile, 300, sms_code)
        pl.execute()
        # 3生成短信验证码
        # ccp = CCP()
        # try:
        #     result = ccp.send_template_sms(mobile, [sms_code, 5], 1)
        # except Exception as e:
        #     logger.error('短信发送异常[mobile：%s ,message:%s]' % (mobile, e))
        #     return Response({'message': 'failed'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
        # else:
        #     if result == 0:
        #         # 返回0 表示发送短信成功
        #         logger.info('短信发送成功[mobile：%s ,sms:%s]' % (mobile, sms_code))
        #         return Response({'message': 'OK'})
        #     else:
        #         # 返回-1 表示发送失败
        #         logger.error('短信发送异常[mobile：%s ]' % mobile)
        #         return Response({'message': 'failed'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
        print(sms_code)
        # send_sms_code.delay(mobile, sms_code)
        return Response({'message': 'OK'})



